package cn.yunhe.control;

import cn.yunhe.entity.User;
import cn.yunhe.server.UserServer;
import cn.yunhe.util.PageLimitUtil;
import cn.yunhe.entity.Blank;
import cn.yunhe.entity.Topic;
import cn.yunhe.server.TopicServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/SelectAllTopic")
public class SelectAllTopic extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TopicServer topicServer = new TopicServer();

        String bId = request.getParameter("bId");
        String bName = request.getParameter("bName");
        Blank blank = new Blank(Integer.parseInt(bId), bName); //新建板块对象

        int totalRow = topicServer.count(blank); //获取总行数
        int totalPage = PageLimitUtil.getTotalePage(totalRow); //获取总页数
        String currentPageIndex = request.getParameter("currentPageIndex");
        int currentPageIndexNo = Integer.parseInt(currentPageIndex); //获取当前页索引编号
        if (currentPageIndexNo < 0) {
            currentPageIndexNo = 0;
        }
        int indexNum = PageLimitUtil.getPageIndex(currentPageIndexNo, totalPage); //对当前页索引进行判断获取有效索引,避免分页索引超界
        if (indexNum > 0) {
            List<Topic> list = topicServer.SelectAllTopic(blank, indexNum); //添加索引号进行查询
            UserServer userServer = new UserServer();
            for (Topic topic:list) {
                int uId = topic.getUser().getuId();
                User user = userServer.getUserById(uId); //获取用户对象全部属性
                topic.setUser(user); //替换topic对象中原来的user对象
            }

            if (list != null && list.size() > 0) {
                request.setAttribute("blank", blank);
                request.setAttribute("topicList", list);
                request.setAttribute("index", indexNum);
                request.setAttribute("totalPage", totalPage);
                request.getRequestDispatcher("selectAllTopic.jsp").forward(request, response);
            } else {
                request.setAttribute("blank", blank);
                request.setAttribute("result", "暂无主贴!!");
                request.getRequestDispatcher("selectAllTopic.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("blank", blank);
            request.setAttribute("result", "暂无主贴!!");
            request.getRequestDispatcher("selectAllTopic.jsp").forward(request, response);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
